<?php
namespace plugins\finance\controller;

use cmf\controller\ApiPluginBaseController;
use think\Db;
use plugins\member\model\MemberModel;
use plugins\store\model\StoreModel;
use plugins\finance\model\FinanceModel;
use plugins\finance\model\FinanceExtractModel;
use plugins\finance\model\FinanceRechargeModel;
use plugins\finance\model\FinanceAccountsModel;
use plugins\pay\lib\Common as LCOM;

class ApiIndexController extends ApiPluginBaseController
{

	public function index()
	{

	}

	//流水记录
	public function finance_list()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);

		$info = $this->getIdentity();

		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}


		$where['finance_type'] = $param['finance_type'];
		$where['finance_type_id'] = $finance_type_id;

		//财务账户
		$finance = ( new FinanceModel )->where($where)->find();

		empty($param['page']) ? $page = 1 : $page = $param['page'];
		empty($param['pagesize']) ? $pagesize = 10 : $pagesize = $param['pagesize'];

		if(!empty($param['money_type'])){
			$where1['money_type'] = $param['money_type'];
		}		
		$where1['finance_id'] = $finance->finance_id;
		//流水记录
		$list = ( new FinanceAccountsModel )
				->field('finance_id',true)
				->where($where1)
				->order('time desc')
				->paginate($pagesize,false,['page'=>$page]);

		//处理流水记录
		foreach ($list as $key => $value) {
			//操作类型
			$value->behavior = $value->behavior($value->behavior);
			//操作时间
			$value->time = date('Y-m-d H:i:s',$value->time);
			//支付方式
			switch ($value->account_type) {
				case 'balance':
					$value->account_type = '余额';
					break;
				case 'alipay':
					$value->account_type = '支付宝';
					break;
				case 'wechatpay':
					$value->account_type = '微信';
					break;
				default:
					# code...
					break;
			}
		}

		return api_json_echo(true,'',$list);
	}


	//账户金额
	public function finance_money()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);

		$info = $this->getIdentity();

		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->field('balance,frozen_money')->where(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id])->find();

		return api_json_echo(true,'',$finance);

	}

	//申请提现
	public function apply_extract()
	{
		$param = $this->request->param();
		checkParam(['money'=>['name'=>'提现金额'],'finance_type'=>['name'=>'账户类型'],'bind_id'=>['name'=>'绑定信息'],'pay_password'=>['name'=>'支付密码']],$param);

		$info = $this->getIdentity();

		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);

		if($finance->pay_password != cmf_password($param['pay_password'])){
			return api_json_echo(false,'支付密码错误');
		}

		//创建提现记录
		$result = $finance->extract($param['bind_id'],$param['money']);

		return api_json_echo($result['status'],$result['message']);

	}

	//申请提现列表
	public function apply_extract_list()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);		

		empty($param['page']) ? $page = 1 : $page = $param['page'];
		empty($param['pagesize']) ? $pagesize = 10 : $pagesize = $param['pagesize'];

		$list = ( new FinanceExtractModel )
				->where(['finance_id'=>$finance->finance_id])
				->field('finance_id',true)
				->order('time desc')
				->paginate($pagesize,false,['page'=>$page]);

		foreach ($list as $key => $value) {

			switch ($value->extract_aim) {
				case 'alipay':
					$value->extract_aim = '支付宝';
					break;
				case 'wechatpay':
					$value->extract_aim = '微信';
					break;				
				default:
					# code...
					break;
			}

			$value->time = date('Y-m-d H:i:s',$value->time);

			$log = json_decode($value->log);
			//倒叙
			$log = array_reverse($log);
			foreach ($log as $k => $v) {
				$v->time = date('Y-m-d H:i:s',$v->time);
			}
			$value->log = $log;
		}

		return api_json_echo(true,'',$list);
	}

	//充值余额
	public function recharge()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型'],'pay_type'=>['name'=>'支付方式'],'money'=>['name'=>'充值金额']],$param);
		$info = $this->getIdentity();	

		//检测支付方式
		$list = LCOM::getPayListWithOn();//已开启的
		$pay_check = in_array($param['pay_type'],$list);
		if(!$pay_check){
			return api_json_echo(false,'请输入正确的支付方式');
		}

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);		

		$result = $finance->recharge($param['pay_type'],$param['money']);

		return api_json_echo($result['status'],$result['message'],$result['data']);

	}

	//充值记录
	public function rechargeList()
	{
		$param = $this->request->param();
		$info = $this->getIdentity();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		empty($param['page']) ? $page = 1 : $page = $param['page'];
		empty($param['pagesize']) ? $pagesize = 10 : $pagesize = $param['pagesize'];

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);	

		//充值列表
		$list = ( new FinanceRechargeModel )
				->field('finance_id,recharge_aim_account',true)
				->where(['finance_id'=>$finance->finance_id])
				->paginate($pagesize,false,['page'=>$page]);

		foreach ($list as $key => $value) {
			$value->time = date('Y-m-d H:i:s',$value->time);
			//支付方式改变
			switch ($value->recharge_aim) {
				case 'alipay':
					$value->recharge_aim = '支付宝';
					break;
				
				case 'wechatpay':
					$value->recharge_aim = '微信';
					break;
				default:
					# code...
					break;
			}
			switch ($value->status) {
				case 1:
					$value->status = '未支付';
					break;
				case 2:
					$value->status = '已支付';
					break;
				case 3:
					$value->status = '已申请退款';
					break;
				case 4:
					$value->status = '退款拒绝';
					break;
				case 5:
					$value->status = '退款成功';
					break;
				default:
					# code...
					break;
			}
		}

		return api_json_echo(true,'',$list);

	}

	//已充值完毕单号申请退款
	public function rechargeRefund()
	{
		$param = $this->request->param();
		$info = $this->getIdentity();
		checkParam(['finance_type'=>['name'=>'账户类型'],'recharge_num'=>['name'=>'充值记录单号']],$param);

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);	

		//单号查询
		$recharge = ( new FinanceRechargeModel )->get(['finance_id'=>$finance->finance_id,'recharge_num'=>$param['recharge_num']]);

		if($recharge == null){
			return api_json_echo(false,'不存在的单号');
		}
		if($recharge->status != 2){
			return api_json_echo(false,'单号状态错误，不是已支付完成的订单，无法申请退款');
		}

		//订单支付超时的退款要求

		if($finance->balance < $recharge->money){
			return api_json_echo(false,'当前账号余额不足无法完成当前操作！');
		}

		$result = $recharge->save(['status'=>3]);

		if($result){
			return api_json_echo(true,'申请成功，请等待审核');
		}

		return api_json_echo(false,'申请失败，请刷新页面充实');

	}

	//绑定列表
	public function appBindList()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);			

		$list = $finance->appBindList();
		
		return api_json_echo(true,'',$list);	

	}


	//增加支付号绑定
	public function appBind()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型'],'pay_type'=>['name'=>'支付方式'],'bind'=>['name'=>'绑定信息']],$param);
		$info = $this->getIdentity();

		//检测支付方式
		$list = LCOM::getPayListWithOn();//已开启的
		$pay_check = in_array($param['pay_type'],$list);
		if(!$pay_check){
			return api_json_echo(false,'请输入正确的支付方式');
		}

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);	

		$result = $finance->appBind($param['pay_type'],$param['bind']);

		return api_json_echo($result['status'],$result['message']);					
	}

	//删除支付号绑定
	public function appBindDel()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型'],'bindid'=>['name'=>'绑定信息id']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}
		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);			
		$result = $finance->appBindDel($param['bindid']);
		return api_json_echo($result['status'],$result['message']);			
	}

	//查询支付密码状态
	public function payPasswordCheck()
	{
		$param = $this->request->param();
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);		
		
		if(empty($finance->pay_password)){
			return api_json_echo(false,'你还未设置支付密码');
		}

		return api_json_echo(true,'你已设置支付密码');

	}

    //修改支付密码
    public function payPasswordUpdate()
    {
        $param = $this->request->param();
        //参数检测
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $finance_type_id = $param['userid'];
        //财务账户
        $finance = ( new FinanceModel )->get(['finance_type'=>'member','finance_type_id'=>$finance_type_id]);
        //没有支付密码的情况
        if(empty($finance->pay_password)){
            //验证参数
            $check['new_pay_password'] = ['type'=>'require|/^\d{6}$/','message'=>'新的支付密码必须为6位的数字'];
            $check['re_pay_password'] = ['name'=>'重复支付密码'];
            checkParam($check,$param);
            if($param['new_pay_password'] != $param['re_pay_password']){
                return api_json_echo(false,'两次输入的密码不相同');
            }

            $result = $finance->save(['pay_password'=>cmf_password($param['new_pay_password'])]);
            if($result){
                return api_json_echo(true,'支付密码修改成功');
            }
            return api_json_echo(false,'支付密码修改失败');
        }else{
            //有支付密码的情况，要输入旧的密码与两次新密码
            //验证参数
            $check['new_pay_password'] = ['type'=>'require|/^\d{6}$/','message'=>'新的支付密码必须为6位的数字'];
            $check['re_pay_password'] = ['name'=>'重复支付密码'];
            $check['old_pay_password'] = ['name'=>'原支付密码'];
            checkParam($check,$param);

            if($param['new_pay_password'] != $param['re_pay_password']){
                return api_json_echo(false,'两次输入的密码不相同');
            }

            if($param['new_pay_password'] == $param['old_pay_password']){
                return api_json_echo(false,'新旧密码不能相同');
            }

            if($finance->pay_password != cmf_password($param['old_pay_password'])){
                return api_json_echo(false,'输入的旧支付密码不正确，请重试');
            }

            $finance->pay_password = cmf_password($param['new_pay_password']);
            $result = $finance->save();
            if($result){
                return api_json_echo(true,'支付密码修改成功');
            }
            return api_json_echo(false,'支付密码修改失败');
        }
    }


	//修改支付密码
	public function payPasswordEdit()
	{
		$param = $this->request->param();
		//参数检测
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);		

		//没有支付密码的情况
		if(empty($finance->pay_password)){
			//验证参数
			$check['new_pay_password'] = ['type'=>'require|/^\d{6}$/','message'=>'新的支付密码必须为6位的数字'];
			$check['re_pay_password'] = ['name'=>'重复支付密码'];
			checkParam($check,$param);
			if($param['new_pay_password'] != $param['re_pay_password']){
				return api_json_echo(false,'两次输入的密码不相同');
			}

			$result = $finance->save(['pay_password'=>cmf_password($param['new_pay_password'])]);
			if($result){
				return api_json_echo(true,'支付密码修改成功');
			}
			return api_json_echo(false,'支付密码修改失败');
		}else{
			//有支付密码的情况，要输入旧的密码与两次新密码
			//验证参数
			$check['new_pay_password'] = ['type'=>'require|/^\d{6}$/','message'=>'新的支付密码必须为6位的数字'];
			$check['re_pay_password'] = ['name'=>'重复支付密码'];
			$check['old_pay_password'] = ['name'=>'原支付密码'];
			checkParam($check,$param);			

			if($param['new_pay_password'] != $param['re_pay_password']){
				return api_json_echo(false,'两次输入的密码不相同');
			}

			if($param['new_pay_password'] == $param['old_pay_password']){
				return api_json_echo(false,'新旧密码不能相同');
			}					

			if($finance->pay_password != cmf_password($param['old_pay_password'])){
				return api_json_echo(false,'输入的旧支付密码不正确，请重试');
			}

			$finance->pay_password = cmf_password($param['new_pay_password']);
			$result = $finance->save();
			if($result){
				return api_json_echo(true,'支付密码修改成功');
			}
			return api_json_echo(false,'支付密码修改失败');
		}

	}

	//检测支付密码
	public function checkPayPassword()
	{
		$param = $this->request->param();
		//参数检测
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);	

		if($finance->pay_password == cmf_password($param['pay_password'])){
			return api_json_echo(true,'支付密码正确');
		}
		return api_json_echo(false,'支付密码错误');
	}

	//忘记支付密码
	public function forgetPayPassword()
	{
		$param = $this->request->param();
		//参数检测
		checkParam(['finance_type'=>['name'=>'账户类型']],$param);
		$info = $this->getIdentity();

		//账户类型检测
		if($param['finance_type'] == 'store'){
			$store = ( new StoreModel )->get(['uid'=>$info->uid]);
			$finance_type_id = $store->store_id;
		}else if($param['finance_type'] == 'member'){
			$finance_type_id = $info->uid;
		}else{
			return api_json_echo(false,'请输入正确的账户类型');
		}

		//财务账户
		$finance = ( new FinanceModel )->get(['finance_type'=>$param['finance_type'],'finance_type_id'=>$finance_type_id]);	

		$check['new_pay_password'] = ['type'=>'require|/^\d{6}$/','message'=>'新的支付密码必须为6位的数字'];
		$check['re_pay_password'] = ['name'=>'重复支付密码'];
		checkParam($check,$param);
		if($param['new_pay_password'] != $param['re_pay_password']){
			return api_json_echo(false,'两次输入的密码不相同');
		}

		$result = $finance->save(['pay_password'=>cmf_password($param['new_pay_password'])]);
		if($result){
			return api_json_echo(true,'支付密码修改成功');
		}
		return api_json_echo(false,'支付密码修改失败');		
	}


}
